﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DZPK.SocketImpl;

namespace DZPK
{
    public class Player
    {
        // for testing 
        private Debugger_ListView listviewDebugger = null;

        private Form1 notifyWnd = null;
        public void SetNotifyWnd(Form1 form)
        {
            notifyWnd = form;

            listviewDebugger = new Debugger_ListView(notifyWnd);

            for (int i = 0; i < 10; i++)
            {
                seatConditionDic[i] = false;
            }
        }

        private TimeSpan HeartBeatInterval = new TimeSpan(0, 0, 1);

        public string username;
        public string password;
        public string userkey;
        public int roomid;
        public int level;
        public int seat;
        public string nick;
        public int coins;
        public int coinsOnTable;
        public int mid;
        public string userother;

        public int tableID;
        public int seatID;
        public Int64 seatMoney;
        public Card card1;      // 手牌
        public Card card2;      // 手牌
        public Int64 needCall;
        public Int64 needRaise;
        public Int64 maxRaise;
        public DateTime promtTime; 
        public PlayerStatus playerStatus;
        public List<Card> cardList;       // 公共牌

        public Action<Player> OnTurn = null;


        private bool bNeedSendHeartBeatMessage = false;
        private DateTime lastHeartBeatTime = DateTime.Now;

        public void MarkPlayerHeartBeatToServer()
        {
            DateTime now = DateTime.Now;
            TimeSpan interval = now - lastHeartBeatTime;

            if (interval > HeartBeatInterval)
            {
                bNeedSendHeartBeatMessage = true;
            }
        }

        public void LoginWeibo()
        {



            // SetLoginContent
        }

        public void EnterRoom(int roomid)
        {

        }

        public void SitDown(int coins)
        {

        }

        public void Analyse(ByteArray byteArray)
        {

        }

        // if option is add, then need to specify the value.
        public void DoAction(CardOption option, int value = 0)
        {

        }

        private RoomsocketSend sender = null;

        public TcpSocket receiver = null;

        public Player()
        {
            receiver = new TcpSocket(this);
            sender = new RoomsocketSend(receiver);
            playerStatus = PlayerStatus.UnLogin;
        }

        public void SetLoginContent(string username, string userkey, int mid, string userother)
        {
            this.username = username;
            this.userkey = userkey;
            this.mid = mid;
            this.userother = userother;

            this.playerStatus = PlayerStatus.LoginReady;
        }

        public void OutputLogMsg(string msg)
        {
            notifyWnd.AddMessage(msg);
        }

        public void ReceiveServerPacket(byte[] bytes, int len)
        {
            if (receiver != null)
            {
                receiver.ReceiveServerPacket(bytes, len);
            }
        }

        public void ProcessServerPacket()
        {
            if (receiver != null)
            {
                receiver.ProcessServerPacket();
            }
        }

        private void ConnectToSever(string ip, int port)
        {
            receiver.connect(ip, port);

            Communication.JoinRead(this);
        }

        public void Test_SendLoginToServer()
        {
            int roomID = 11;

            ServerInfo oIpPort = PlayEngine.GetPlayEnginInstance().GetTableIpPortFromTableIndex(roomID);

            ConnectToSever(oIpPort.serverIP, Convert.ToInt32(oIpPort.serverPort));

            int mid = 16041193;
            string userkey = "89be5f58f9b45c7e07fe7544d7388c61";// "19c2e770d46b29205dc9a0e6b3f0af9e";// ""670f721e5cbf00f7f3c0639a4b387b0f"";'28c0043073d1f812f4492de7c2c931bc',
            string username = "fddadsfdafhenry";
            string imgurl = "";
            string level = "2";
            string userOther = @"{""maxWinChips"":774,""askfor"":0,""bestCards"":""[776,520,1032,268,780]"",""gameCount"":145,""city"":""北京 东城区"",""winCount"":26,""maxOwnChips"":30435,""sitID"":117,""sexID"":0,""showVip"":0,""score"":0,""sngr1WinCount"":null,""siteAdmin"":0,""sngr2WinCount"":null,""prize"":7,""sngr3WinCount"":null,""totalPrize"":0,""showHelp"":0,""sngr1LoseCount"":null,""diamondnew"":[],""sngr2LoseCount"":null,""unid"":111000,""sngr3LoseCount"":null,""school"":"""",""sngwinCount"":0,""sname"":"""",""sngloseCount"":0,""association"":""北京 东城区"",""weiboPage"":""http://weibo.com/3560106970"",""privacyControl"":""[0,0]"",""addGameTime"":""2013-06-26"",""platformType"":0,""bestCardType"":8,""home"":"""",""userSkillExp"":91,""gifturl"":"""",""loseCount"":91,""mbig"":""http://tp3.sinaimg.cn/3560106970/180/0/1"",""experience"":162,""homePage"":"" http://game.weibo.com/center/user?userId=3560106970"",""gameCountToday"":34,""diamond"":[],""mfcount"":0,""msgCount"":2,""sitemid"":""3560106970"",""vipLevel"":0,""mactivetime"":""2013-07-14"",""sinav"":""0"",""sinavreason"":null,""sinavtype"":-1,""integral"":75,""mttTopCount"":""0""}";
            string gift = "";

            SendLoginToServer(roomID, mid, userkey, username, imgurl, level, userOther, gift);
        }

        public void SendLoginToServer(int roomid, int mid, string usrkey, string usrname, string imgurl, string level, string usrother, string gift)
        {
            this.tableID = roomid;
            sender.SendLogin(roomid, mid, userkey, username, imgurl, level, usrother, gift);
        }

        public void SendRequestRoomInfo()
        {
            sender.SendRequestRoomInfo();
        }

        public void SendClientEchoConnection()
        {
            sender.SendClientEchoConnection();
        }

        public void SendClientChipin(int chipinAction, Int64 chipinMoney, string usrKey)
        {
            sender.RequestChipin(chipinAction, chipinMoney, usrKey);
        }

        public void SendClientSitRequest(int seatID, Int64 chipsBuy, int isAutoBuy = 0)
        {
            sender.SendSitRequset(seatID, chipsBuy, isAutoBuy);
        }

        public void SendClientUpdateUserInfo()
        {
            sender.SendUserInfosUpdate();
        }

        public void SendClientUserStand()
        {
            sender.RequestUserStand();
        }

        public void SendClientUserLogout()
        {
            sender.SendLogOut();
        }

        public void ProcessLoginSuccess(string roomName, int smallBlind, Int64 buyMinChips, Int64 buyMaxChips, Int64 playerCoins, int chipinTime)
        {
            listviewDebugger.ProcessLoginSuccess(roomName, smallBlind, buyMinChips, buyMaxChips, playerCoins, chipinTime);

            this.playerStatus = PlayerStatus.EnterRoomSuccess;
        }

        public void ProcessBindSuccessResponse(string roomname, int smallblind, Int64 buyMinChips, Int64 buyMaxChips, int seatID, Int64 usrCoin, int card1, int card2)
        {
            listviewDebugger.ProcessBindSuccessResponse(roomname, smallblind, buyMinChips, buyMaxChips, seatID, usrCoin, card1, card2);

            this.playerStatus = PlayerStatus.EnterRoomSuccess;
        }

        public void ProcessRoomInfoResponse(int gameState, int maxPlayCount, int gameBid, int dealer, int size, List<int> cardList)
        {
            listviewDebugger.ProcessRoomInfoResponse(gameState, maxPlayCount, gameBid, dealer, size, cardList);
        }

        public void ProcessPlayerInfoResponse(int seatID, int mid, Int64 usrCoins, string usrname, Int64 bureauMoney, Int64 seatChips, int isPlay, int chipinType)
        {
            listviewDebugger.ProcessPlayerInfoResponse(seatID, mid, usrCoins, usrname, bureauMoney, seatChips, isPlay, chipinType);

            seatConditionDic[seatID] = true;

            this.playerStatus = PlayerStatus.ReadyToSit;
        }

        public void ProcessUserActionResponse(int seatID, int cardOption, Int64 seatMoney, Int64 seatChips, Int64 usrCoins)
        {
            listviewDebugger.ProcessUserActionResponse(seatID, cardOption, seatMoney, seatChips, usrCoins);
        }

        public void ProcessUserSitResponse(int seatID, int mid, Int64 usrCoins, string usrname, Int64 seatMoney)
        {
            listviewDebugger.ProcessUserSitResponse(seatID, mid, usrCoins, usrname, seatMoney);

            seatConditionDic[seatID] = true;

            this.playerStatus = PlayerStatus.SitSuccess;
        }

        public void ProcessChipinPromptResponse(int seatID, Int64 needCall, Int64 needRaise, Int64 maxRaise)
        {
            listviewDebugger.ProcessChipinPromptResponse(seatID, needCall, needRaise, maxRaise);

            if (seatID == this.seatID)
            {
                //  需要做动作
                this.needCall = needCall;
                this.needRaise = needRaise;
                this.maxRaise = maxRaise;

                promtTime = DateTime.Now;
            }
        }

        public void ProcessUserStandResponse(int seatID, string usrname, Int64 usrCoins)
        {
            listviewDebugger.ProcessUserStandResponse(seatID, usrname, usrCoins);

            seatConditionDic[seatID] = false;

            this.seatID = -1;
        }

        public void ProcessSysMsgResponse(string sysMsg)
        {
            listviewDebugger.ProcessSysMsgResponse(sysMsg);
        }

        public void ProcessDealFolpResponse(int card1, int card2, int card3)
        {
            listviewDebugger.ProcessDealFolpResponse(card1, card2, card3);

            this.playerStatus = PlayerStatus.FlopCardRound;
        }

        public void ProcessDealPrefLop(int seatID, int card1, int card2)
        {
            listviewDebugger.ProcessDealPrefLop(seatID, card1, card2);

            this.playerStatus = PlayerStatus.PreFlop;
        }

        public void ProcessDealTurn(int cardTurn)
        {
            listviewDebugger.ProcessDealTurn(cardTurn);
        }

        public void ProcessLoginFailedResponse(int reasonID)
        {
            listviewDebugger.ProcessLoginFailedResponse(reasonID);
        }

        public void ProcessUserLogOutResponse(int mid, string usrname)
        {
            listviewDebugger.ProcessUserLogOutResponse(mid, usrname);

            if (mid == this.mid)
            {
                Communication.LeaveRead(this);
            }
        }
        public void ProcessLoginOutSuccessResponse()
        {
            listviewDebugger.ProcessLoginOutSuccessResponse();

            Communication.LeaveRead(this);
        }

        public void ProcessConnectFailedResponse()
        {
            listviewDebugger.ProcessConnectFailedResponse();
        }

        public void ProcessSitFailedResponse(int failreasonID)
        {
            listviewDebugger.ProcessSitFailedResponse(failreasonID);
        }

        public void ProcessUserNoticeAllResponse(int seatID, int noticeCmd, string noticeContent)
        {
            
        }

        public void ProcessFinalRoundResponse()
        {
            
        }

        public void ProcessKickUserResponse(int mid, int seatID)
        {
            
        }

        public void ProcessSitSuccessResponse(int seatID, string usrname, Int64 seatMoney)
        {
            listviewDebugger.ProcessSitSuccessResponse(seatID, usrname, seatMoney);

            this.seatID    = seatID;
            this.seatMoney = seatMoney;
        }

        public void ProcessDealRiverResponse(int cardRiver)
        {
            listviewDebugger.ProcessDealRiverResponse(cardRiver);
        }

        public void ProcessFinalGameResponse(List<GameResult> result)
        {
            listviewDebugger.ProcessFinalGameResponse(result);
        }

        public void ProcessUserChipInErrResponse()
        {
            listviewDebugger.ProcessUserChipInErrResponse();
        }

        public void ProcessUserUpdataExpResponse(string expUpdateString)
        {
            listviewDebugger.ProcessUserUpdataExpResponse(expUpdateString);
        }

        public void ProcessGameStartResponse(int dealer, List<StartGamePlayerResponse> startPlayerList)
        {
            listviewDebugger.ProcessGameStartResponse(dealer, startPlayerList);
        }

        public void ShowPreflopResponse(List<UserHandCardResponse>  usrHandCardList)
        {
            
        }

        public void FindFreeSeatToSit()
        {
            
        }

        private Dictionary<int, bool> seatConditionDic = new Dictionary<int, bool>();
        public void Test_FindFreeSeatToSit()
        {
            int seatID = 0;

            for (int i = 1; i < 10; i++)
            {
                if (seatConditionDic[i] == false)
                {
                    seatID = i;
                    break;
                }
            }

            if (seatID != 0)
            {
                SendClientSitRequest(seatID, 300);
            }
        }
    }
}
